package com.sihan.swvp.action.sys;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sihan.swvp.action.BaseAction;
import com.sihan.swvp.common.CommonUtil;
import com.sihan.swvp.entity.sys.Menu;
import com.sihan.swvp.entity.sys.User;
import com.sihan.swvp.service.sys.LogService;
import com.sihan.swvp.service.sys.MenuService;
@Controller
@RequestMapping("/menu")
public class MenuAction extends BaseAction{
	@Autowired
	MenuService menuService;
	
	@Autowired
	public LogService logService;
	
	@ResponseBody
	@RequestMapping("/getMenu")
	public List<Map<String,Object>> getMenu(@RequestParam(required=false) String node){
		User user = getLoginUser();
		List<Map<String,Object>> list = menuService.getMenuByParent(user.getId(),node);
		return list;
	} 
	
	@ResponseBody
	@RequestMapping("/getMenu3")
	public List<Map<String,Object>> getMenu3(){
		User user = getLoginUser();
		List<Map<String,Object>> list = menuService.getMenu3(user.getId());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/getMenu2")
	public List<Map<String,Object>> getMenu2(@RequestParam String node){
		User user = getLoginUser();
		List<Map<String,Object>> list = menuService.getMenuByParent(user.getId(),node);
		return list;
	} 
	
	@ResponseBody
	@RequestMapping("/getPrivMenu")
	public List<Map<String,Object>> getPrivMenu(@RequestParam("user")Long user,@RequestParam String node){
		List<Map<String,Object>> list = menuService.getMenuByParent(user,node);
		return list;
	} 
	
	@ResponseBody
	@RequestMapping(value="/getFolder")
	public List<Map<String,Object>> getFolder(@RequestParam String node){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list = menuService.getFolderByParent(node);
		return list;
	}
	
	@ResponseBody
	@RequestMapping(value="/getIcon")
	public void getIcon(HttpServletResponse response,@RequestParam(required = true) String id){
		ServletOutputStream output = null;
		InputStream in = null;
		try {
			output = response.getOutputStream();
			Menu menu = menuService.getIcon(id);
			byte[] bytes= menu == null ? null : menu.getIcon();
			if(null == bytes){
				if(menu.getLeaf() == 0){
					in = new FileInputStream(getRootPath()+"images/icons/folder1.gif");
				}
				else{
					in = new FileInputStream(getRootPath()+"images/icons/grid.png");
				}
				bytes = new byte[in.available()];
				in.read(bytes);
			}
			output.write(bytes);
		    output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		finally{
			CommonUtil.close(output);
			CommonUtil.close(in);
		}
	}
	
	@ResponseBody
	@RequestMapping(value="/addMenu")
	public Object addMenu(
			@RequestParam(required = true) String id,
			@RequestParam(required = true,defaultValue="0") String pid,
			@RequestParam String index,
			@RequestParam(required = true) String text,
			@RequestParam(required = true,defaultValue="0") String linktype,
			@RequestParam String link,
			@RequestParam String leaf
			)
	{
		try {
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("id", id);
			params.put("pid", pid);
			params.put("index", CommonUtil.isEmptyString(index) ? "0" : index);
			params.put("text", text);
			params.put("linktype", linktype);
			params.put("link", link);
			params.put("leaf", leaf);
			params.put("upuser", getLoginUser().getId());
			if(null != id && !"".equals(id)){
				
				menuService.updateMenu(params);
				logService.addUserLog("修改菜单", "菜单", getLoginUser().getId(), "修改菜单："+text,getRemoteAddr(),1,1);
				
			}
			else{
				int n = menuService.getMenuByNameCounts(params.get("text").toString());
				if(n > 0){
					logService.addUserLog("添加菜单", "菜单", getLoginUser().getId(), "菜单："+text+"已存在",getRemoteAddr(),0,1);
					return successMsg("已存在此类名称的菜单，请重新输入。"); 
					
				}
				menuService.addMenu(params);
				logService.addUserLog("添加菜单", "菜单", getLoginUser().getId(), "添加菜单："+text,getRemoteAddr(),1,1);
			}
		} catch (Exception e) {
			// TODO: handle exception
			return failMsg();
		}
		
		
		return successMsg("保存成功");
	} 
	
	@ResponseBody
	@RequestMapping(value="/deleteMenu")
	public Object deleteMenu(@RequestParam String id,String menutext){
		try {
			menuService.deleteMenu(id,getLoginUser());
			logService.addUserLog("删除菜单", "菜单", getLoginUser().getId(), "删除菜单："+menutext,getRemoteAddr(),1,1);
		} catch (Exception e) {
			// TODO: handle exception
			logService.addUserLog("删除菜单", "菜单", getLoginUser().getId(), "删除菜单："+menutext,getRemoteAddr(),0,1);
			failMsg("服务器异常");
		}
		return successMsg();
	} 
	
	@ResponseBody
	@RequestMapping("/getNavigationMenu")
	public Object getNavigationMenu(){
		User user = getLoginUser();
		List<Map<String,Object>> list = menuService.getNavigationMenu(user.getId());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/getUserMenu")
	public Object getUserMenu(){
		User user = getLoginUser();
		List<Map<String,Object>> list = menuService.getUserMenu(user.getId());
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/addUserMenu")
	public Object addUserMenu(@Param("menuid")Integer menuid){
		 try {
			 User user = getLoginUser();
			 Map<String, Object> param=new HashMap();
			 
			 param.put("userid", user.getId());
			 param.put("menuid", menuid);
			 Map<String, Object> validate=menuService.getUserMenuValidate(param);
			 param.put("sort", CommonUtil.o2int(validate.get("maxSort"))+1);
			 Integer number=CommonUtil.o2int(validate.get("number"));
			 if(number !=0){
				return failMsg("该菜单已移入");
			 }
			 menuService.addUserMenu(param);
			 
//			 sort();
		} catch (Exception e) {
			e.printStackTrace();
			failMsg("移入失败");
		}
		 return successMsg();
	}
	
	
	/**
	 * 排序
	 * @param idArr
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateUserMenuSort")
	public Object updateUserMenuSort(@Param("idArr")String idArr){
		try {
			Map<String, Object> param=new HashMap<String, Object>();
			User user = getLoginUser();
			param.put("userid", user.getId());
			String[] ids=idArr.split(",");
			for (int i = 0; i < ids.length; i++) {
				param.put("menuid", ids[i]);
				param.put("sort", i+1);
				menuService.updateUserMenuSort(param);	
			}
			
			return successMsg("");
		} catch (Exception e) {
			e.printStackTrace();
			return failMsg("服务器异常");
		}
	}
	
	
	@ResponseBody
	@RequestMapping("/deleteUserMenu")
	public Object deleteUserMenu(@Param("menuidArr")Integer[] menuidArr){
		try {
			Map<String, Object> param=new HashMap<String, Object>();
			User user = getLoginUser();
			param.put("menuidArr", Arrays.asList(menuidArr));
			param.put("userid", user.getId());
			menuService.deleteUserMenu(param);
//			sort();
			return successMsg("");
		} catch (Exception e) {
			e.printStackTrace();
			return failMsg();
		}
	}
	
}
